package com.example.demo.Impl;

import com.example.demo.dto.CollegeManagementResultDTO;
import com.example.demo.dto.CollegeManagementResultDTO.StudentResultDTO;
import com.example.demo.entity.MbtiResult;
import com.example.demo.entity.Organization;
import com.example.demo.entity.Student;
import com.example.demo.repository.MbtiResultRepository;
import com.example.demo.repository.OrganizationRepository;
import com.example.demo.repository.StudentRepository;
import com.example.demo.service.CollegeManagementService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class CollegeManagementServiceImpl implements CollegeManagementService {

    @Autowired
    private OrganizationRepository organizationRepository;

    @Autowired
    private StudentRepository studentRepository;

    @Autowired
    private MbtiResultRepository mbtiResultRepository;

    @Override
    public List<CollegeManagementResultDTO> getAllCollegeResults() {
        List<Organization> colleges = organizationRepository.findByType(Organization.OrgType.college);

        List<CollegeManagementResultDTO> resultList = new ArrayList<>();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

        for (Organization college : colleges) {
            List<Organization> majors = college.getChildren();
            List<Organization> classes = new ArrayList<>();
            majors.forEach(major -> classes.addAll(major.getChildren()));

            List<Student> students = studentRepository.findByClazzIn(classes);

            List<MbtiResult> results = mbtiResultRepository.findByStudentIdIn(
                    students.stream().map(Student::getId).collect(Collectors.toList())
            );

            Map<Long, Student> studentMap = students.stream()
                    .collect(Collectors.toMap(Student::getId, s -> s));

            List<StudentResultDTO> studentResultDTOs = results.stream().map(r -> {
                Student student = studentMap.get(r.getStudentId());
                StudentResultDTO dto = new StudentResultDTO();
                dto.setStudentName(student.getName());
                dto.setStudentNo(student.getStudentNo());
                dto.setMbtiType(r.getMbtiType());
                dto.setTestTime(r.getTestTime().format(formatter));
                return dto;
            }).collect(Collectors.toList());

            CollegeManagementResultDTO dto = new CollegeManagementResultDTO();
            dto.setId(college.getId());
            dto.setName(college.getName());
            dto.setResults(studentResultDTOs);

            resultList.add(dto);
        }

        return resultList;
    }
}
